<template>
   <div class="logo-container">
      <img :src="logo" alt="logo" class="logo" />
      <h1 class="title">{{ title }}</h1>
    </div>
  <div class="chat-container">
   
    <!-- 消息展示区域 -->
    <div class="message-list" ref="messageListRef">
      <t-chat
        ref="chatRef"
        layout="both"
        @clear="clearConfirm"
        :reverse="false"
        :clear-history="messages.length > 1 && !isLoading"
      >
        <template v-for="msg in messages">
          <t-chat-item
            :avatar="
              msg.role === 'user' ? userAvatar : aiAvatar
            "
            :name="msg.role === 'user' ? userName : aiName"
            :role="msg.role === 'user' ? 'user' : 'assistant'"
            :content="msg.content || '&nbsp;'"
            variant="outline"
          >
            <t-chat-content
              role="assistant"
              :content="msg.content"
              variant="base"
            >
            </t-chat-content>
          </t-chat-item>
        </template>
      </t-chat>
    </div>

    <!-- 输入区域，固定在底部 -->
     <!-- 666ces -->
    <div class="input-fixed-container">
      <t-chat-input
        v-model="inputText"
        :stop-disabled="isLoading"
        @send="sendMessage"
        @stop="handleStop"
      >
      </t-chat-input>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from "vue";
import { Chat } from "@tdesign-vue-next/chat";
import { useChat, type Message } from "../services/chatService";
const title = import.meta.env.VITE_title;
const userAvatar = import.meta.env.VITE_userAvatar;
const userName = import.meta.env.VITE_userName;
const aiAvatar = import.meta.env.VITE_aiAvatar;
const aiName = import.meta.env.VITE_aiName;
const initMessage = import.meta.env.VITE_initMessage;
const logo = import.meta.env.VITE_logo;

const TChat = Chat;
const inputText = ref("");
const isLoading = ref(false);
const messageListRef = ref<HTMLElement | null>(null);
const chatRef = ref(null);

// 使用聊天服务
const { streamChat, error } = useChat();

// 初始化消息列表
const initialMessages: Message[] = [
  {
    role: "assistant",
    content: initMessage,
  },
];

// 从本地存储加载消息
const loadMessagesFromLocalStorage = (): Message[] => {
  try {
    const savedMessages = localStorage.getItem("chat_messages");
    if (savedMessages) {
      return JSON.parse(savedMessages);
    }
  } catch (e) {
    console.error("加载本地聊天记录失败:", e);
  }
  return [...initialMessages];
};

// 保存消息到本地存储
const saveMessagesToLocalStorage = (msgs: Message[]) => {
  try {
    localStorage.setItem("chat_messages", JSON.stringify(msgs));
  } catch (e) {
    console.error("保存聊天记录失败:", e);
  }
};

const messages = ref<Message[]>(loadMessagesFromLocalStorage());

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    setTimeout(() => {
      // 直接滚动message-list元素
      if (messageListRef.value) {
        messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
        
        // 滚动内部聊天面板
        const chatPanel = messageListRef.value.querySelector('.t-chat__panel');
        if (chatPanel) {
          chatPanel.scrollTop = chatPanel.scrollHeight;
        }
        
        // 滚动内部聊天面板主体
        const panelBody = messageListRef.value.querySelector('.t-chat__panel-body');
        if (panelBody) {
          panelBody.scrollTop = panelBody.scrollHeight;
        }
        
        // 尝试滚动其他可能的容器
        messageListRef.value.querySelectorAll('.t-chat, .t-chat__panel, .t-chat__panel-body').forEach(el => {
          if (el instanceof HTMLElement) {
            el.scrollTop = el.scrollHeight;
          }
        });
      }
    }, 50); // 延长延时确保DOM完全更新
  });
};

// 监听消息变化，保存到本地存储并滚动到底部
watch(
  messages,
  (newMessages) => {
    if (newMessages.length > 0) {
      saveMessagesToLocalStorage(newMessages);
      scrollToBottom();
    }
  },
  { deep: true }
);

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom();
});

// 停止生成回复
const handleStop = function () {
  isLoading.value = false;
  // 实际中可能需要调用API取消请求
};
// 清空消息
const clearConfirm = function () {
  // 清除本地存储
  localStorage.removeItem("chat_messages");
  
  // 恢复到初始状态，显示初始消息
  messages.value = [...initialMessages];
};
// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || isLoading.value) return;

  // 添加用户消息
  const userMessage: Message = {
    role: "user",
    content: inputText.value.trim(),
  };
  messages.value.push(userMessage);

  // 清空输入框
  inputText.value = "";

  // 创建包含历史消息的数组
  const messageHistory = [...messages.value];

  // 添加AI消息占位
  messages.value.push({
    role: "assistant",
    content: "",
  });

  // 设置加载状态
  isLoading.value = true;

  // 流式接收AI回复
  await streamChat(
    messageHistory,
    (chunk) => {
      // 更新最后一条消息（AI回复）
      if (messages.value.length > 0) {
        const lastMessage = messages.value[messages.value.length - 1];
        if (lastMessage.role === "assistant") {
          lastMessage.content += chunk;
        }
      }
      // 每次收到新内容后滚动到底部
      scrollToBottom();
    },
    () => {
      // 消息接收完成
      isLoading.value = false;
      // 确保消息完成后滚动到底部
      scrollToBottom();
    }
  );

  if (error.value) {
    // 如果有错误，显示错误消息
    const lastMessage = messages.value[messages.value.length - 1];
    if (lastMessage.role === "assistant") {
      lastMessage.content = `抱歉，发生了错误: ${error.value}`;
    }
    isLoading.value = false;
  }
};
</script>

<style scoped>
.chat-container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: hidden;
  padding-bottom: 80px; /* 为固定的输入框留出空间 */
  padding-top: 80px; /* 为固定的logo留出空间 */
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  max-height: calc(100vh - 200px); /* 设置最大高度，减去logo和输入框的高度 */
  display: flex;
  flex-direction: column;
}

/* 确保t-chat组件填满message-list容器 */
.message-list :deep(.t-chat) {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 确保聊天面板主体可滚动 */
.message-list :deep(.t-chat__panel) {
  flex: 1;
  overflow-y: auto;
}

.message-list :deep(.t-chat__panel-body) {
  overflow-y: auto;
}

.input-fixed-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 20px;
  z-index: 10;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  left: 50%;
  transform: translateX(-50%);
}

.input-area {
  padding: 20px;
  background: var(--td-bg-color-container);
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
}

.input-box {
  --td-input-height: 48px;
}
.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 10px 20px;
  z-index: 10;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  left: 50%;
  transform: translateX(-50%);
}
.logo {
  width: 120px;
  height: 40px;
  margin-right: 10px;
}
.title {
  font-size: 36px;
  font-weight: bold;
}
</style>
